﻿using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Cache.Repositories;
using IMClient.Model;
using IMClient.Model.DataBase;
using IMClient.Model.DTO;
using IMClient.Model.UI;
using IMClient.View;

namespace IMClient.ViewModels
{
    public partial class ContactsPageViewModel : ObservableObject
    {
        private readonly FriendCacheRepository _friendRepository;
        
        private readonly GroupCacheRepository _groupRepository;

        private readonly FriendNotificationViewModel _friendNotificationViewModel;

        private readonly GroupNotificationViewModel _groupNotificationViewModel;

        [ObservableProperty] private object? currentView; // 当前视图（用于切换显示的内容）

        [ObservableProperty] private object? friendsOrGroupsList;

        [ObservableProperty] private string searchContent = string.Empty;

        private readonly ContactsPageFriendsListViewModel _friendsListViewModel;

        private readonly ContactsPageGroupsListViewModel _groupsListViewModel;

        public static event Action<ChatParticipantViewModel>? ParticipantAdded;

        public ContactsPageViewModel()
        {
            _friendRepository = FriendCacheRepository.Instance;
            _groupRepository = GroupCacheRepository.Instance;
            _friendNotificationViewModel = new FriendNotificationViewModel();
            _groupNotificationViewModel=new GroupNotificationViewModel();
            _friendsListViewModel = new ContactsPageFriendsListViewModel();
            _groupsListViewModel = new ContactsPageGroupsListViewModel();

            _friendsListViewModel.CurrentViewChanged += HandleCurrentViewChanged;
            _groupsListViewModel.CurrentViewChanged += HandleCurrentViewChanged;

            _groupsListViewModel.GroupsListUpdated += () =>
            {
                UpdateFriendsAndGroupsList(SearchContent); // 刷新群组和好友显示
            };

            ShowFriends();
        }

        [RelayCommand]
        private void InitiateGroupChat()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var window = new InitiateGroupChatWindow();
                window.ShowDialog();
            });
        }

        [RelayCommand]
        private void AddFriend()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var window = new AddFriendWindow();
                window.ShowDialog();
            });
        }

        [RelayCommand]
        private void AddGroup()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var window = new AddGroupWindow();
                window.ShowDialog();
            });
        }

        [RelayCommand]
        public void CheckFriendNotification()
        {
            CurrentView = new FriendNotificationView { DataContext = _friendNotificationViewModel };
        }

        [RelayCommand]
        public void CheckGroupNotification()
        {
            CurrentView = new GroupNotificationView { DataContext = _groupNotificationViewModel };
        }

        public async Task AddFriendAccept(string userId, FriendViewModel friendViewModel)
        {
            // 添加到UI
            _friendsListViewModel.FriendsList.Add(friendViewModel);
            _friendsListViewModel.FilteredFriends.Add(friendViewModel);

            
            // 从数据库加载好友列表
            var cachedFriends = await _friendRepository.GetCachedFriendsAsync(userId);
            cachedFriends.Add(new FriendDataBase
            {
                UserId = userId,
                FriendId = friendViewModel.Id,
                FriendName = friendViewModel.Name,
                FriendAvatar = friendViewModel.Avatar,
                LastUpdateTime = DateTime.Now
            });
            // 更新数据库
            await _friendRepository.CacheFriendsAsync(userId, cachedFriends);
            // 更新User
            User.FriendList?.Add(new FriendDto
            {
                UserId = friendViewModel.Id, UserName = friendViewModel.Name, Avatar = friendViewModel.Avatar
            });
            ParticipantAdded?.Invoke(friendViewModel);
        }

        public async Task JoinGroupAccept(string userId, GroupViewModel groupViewModel)
        {
            // 添加待UI
            _groupsListViewModel.GroupsList.Add(groupViewModel);
            _groupsListViewModel.FilteredGroups.Add(groupViewModel);

            
            // 从数据库加载群组列表
            var cachedGroups = await _groupRepository.GetCachedGroupsAsync(userId);
            cachedGroups.Add(new GroupDataBase
            {
                UserId = userId,
                GroupId = groupViewModel.Id,
                GroupName = groupViewModel.Name,
                GroupAvatar = groupViewModel.Avatar,
                Creator = groupViewModel.Creator!,
                LastUpdateTime = DateTime.Now
            });
            // 更新数据库
            await _groupRepository.CacheGroupsAsync(userId, cachedGroups);
            // 更新User
            User.GroupList?.Add(new GroupDto
            {
                GroupId = groupViewModel.Id, GroupName = groupViewModel.Name, Avatar = groupViewModel.Avatar
            });
            ParticipantAdded?.Invoke(groupViewModel);
        }

        // 返回好友通知ViewModel
        public FriendNotificationViewModel GetFriendNotificationViewModel()
        {
            return _friendNotificationViewModel;
        }
        
        // 返回群组通知ViewModel
        public GroupNotificationViewModel GetGroupNotificationViewModel()
        {
            return _groupNotificationViewModel;
        }

        [RelayCommand]
        private void ShowFriends()
        {
            FriendsOrGroupsList = new ContactsPageFriendsList { DataContext = _friendsListViewModel };
        }

        [RelayCommand]
        private void ShowGroups()
        {
            FriendsOrGroupsList = new ContactsPageGroupsList { DataContext = _groupsListViewModel };
        }

        // 处理事件
        private void HandleCurrentViewChanged(object newView)
        {
            CurrentView = newView;
        }

        partial void OnSearchContentChanged(string value)
        {
            UpdateFriendsAndGroupsList(value);
        }

        private async void UpdateFriendsAndGroupsList(string searchContent)
        {
            // 如果是好友列表
            if (_friendsListViewModel.FriendsList.Count != 0)
            {
                var filteredFriends = _friendsListViewModel.FriendsList
                    .Where(friend => friend.Name.Contains(searchContent, StringComparison.OrdinalIgnoreCase))
                    .ToList();

                await Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    _friendsListViewModel.FilteredFriends.Clear();
                    foreach (var friend in filteredFriends)
                    {
                        _friendsListViewModel.FilteredFriends.Add(friend);
                    }
                });
            }

            // 如果是群组列表
            if (_groupsListViewModel.GroupsList.Count != 0)
            {
                var filteredGroups = _groupsListViewModel.GroupsList
                    .Where(group => group.Name.Contains(searchContent, StringComparison.OrdinalIgnoreCase))
                    .ToList();

                await Application.Current.Dispatcher.BeginInvoke(() =>
                {
                    _groupsListViewModel.FilteredGroups.Clear();
                    foreach (var group in filteredGroups)
                    {
                        _groupsListViewModel.FilteredGroups.Add(group);
                    }
                });
            }
        }

    }
}